﻿using System;
using Microsoft.SharePoint;
using WoltersKluwer.SPChainGang.Core.ExtensionMethods;
using JohnHolliday.Caml.Net;

namespace WoltersKluwer.SPChainGang.Core.Data.Entity
{
    public class BaseEntity
    {
        public SPListItem Item { get; private set; }

        public BaseEntity(SPListItem item)
        {
            Item = item;
        }

        public int Id
        {
            get
            {
                return Item.ID;
            }
        }

        public virtual string Title
        {
            get
            {
                return Item.Title;
            }
            set
            {
                Item.SetProperty("Title", value);
            }
        }

        public virtual void Update()
        {
            MakeUnsafeUpdate(Item.Update);
        }

        public void SystemUpdate()
        {
            MakeUnsafeUpdate(Item.SystemUpdate);
        }

        public ISecurableObject GetSecurableObject()
        {
            return Item;
        }

        private void MakeUnsafeUpdate(Action update)
        {
            bool allowUnsafeUpdates = Item.Web.AllowUnsafeUpdates;
            try
            {
                Item.Web.AllowUnsafeUpdates = true;
                update();
            }
            finally
            {
                Item.Web.AllowUnsafeUpdates = allowUnsafeUpdates;
            }

        }

        protected SPFieldLookupValue GetLookupValue(string lookupValue, string fieldInternalName)
        {
            var field = (SPFieldLookup)Item.Fields.GetFieldByInternalName(fieldInternalName);

            string queryText = CAML.Where(CAML.Eq(CAML.FieldRef(field.LookupField), CAML.Value(lookupValue)));
            SPList lookupList = Item.Web.Lists[new Guid(field.LookupList)];

            SPListItemCollection lookupItems =
                lookupList.GetItems(new SPQuery() { Query = queryText });

            if (lookupItems.Count > 0)
            {
                int lookupId =
                    Convert.ToInt32(lookupItems[0][SPBuiltInFieldId.ID]);

                return new SPFieldLookupValue(lookupId, lookupValue);
            }
            return null;
        }
    }
}
